
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { HardDrive, CheckCircle, AlertCircle, Cloud, Server, Database } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { http } from '@/utils/http';

const StorageSourceChoice = ({ toggleSidebar }) => {
  const navigate = useNavigate();
  const [storageSources, setStorageSources] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedSource, setSelectedSource] = useState(null);

  // 存储类型图标映射
  const getStorageIcon = (sourceCode) => {
    switch (sourceCode) {
      case 'LOCAL':
        return HardDrive;
      case 'Amazon':
        return Cloud;
      case 'ALY_OSS':
        return Server;
      case 'TXY_OSS':
        return Cloud;
      case 'MINIO':
        return Database;
      case 'FTP':
        return Server;
      default:
        return HardDrive;
    }
  };

  // 获取存储类型显示名称
  const getStorageTypeName = (sourceCode) => {
    switch (sourceCode) {
      case 'LOCAL':
        return '本地存储';
      case 'Amazon':
        return 'Amazon S3';
      case 'ALY_OSS':
        return '阿里云OSS';
      case 'TXY_OSS':
        return '腾讯云COS';
      case 'MINIO':
        return 'MinIO';
      case 'FTP':
        return 'FTP服务器';
      default:
        return sourceCode;
    }
  };

  // 获取存储源列表
  const fetchStorageSources = async () => {
    setIsLoading(true);
    try {
      const response = await http.get('/storage/stg-source/self');
      
      if (response.code === "200" && response.msg === "success" && response.data) {
        const availableSources = response.data.filter(source => 
          source.isEnabled === 1 && source.sourceStatus === 'ENABLED'
        );
        
        setStorageSources(availableSources);
        
        const defaultSource = availableSources.find(source => source.isDefault === 1);
        if (defaultSource) {
          setSelectedSource(defaultSource);
        }
      } else {
        console.error('获取存储源失败:', response);
        setStorageSources([]);
      }
    } catch (error) {
      console.error('获取存储源失败:', error);
      setStorageSources([]);
    } finally {
      setIsLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchStorageSources();
  }, []);

  // 选择存储源
  const handleSelectSource = (source) => {
    setSelectedSource(source);
  };

  // 双击存储源卡片直接进入
  const handleDoubleClickSource = (source) => {
    if (source.isEnabled === 1 && source.sourceStatus === 'ENABLED') {
      navigate(`/storage/my-file?sourceId=${source.sourceId}`);
    }
  };

  // 获取状态徽章
  const getStatusBadge = (sourceStatus, isEnabled) => {
    if (!isEnabled || sourceStatus !== 'ENABLED') {
      return (
        <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
          <AlertCircle className="w-3 h-3 mr-1" />
          不可用
        </Badge>
      );
    }
    
    return (
      <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
        <CheckCircle className="w-3 h-3 mr-1" />
        可用
      </Badge>
    );
  };

  return (
    <div className="flex flex-col h-screen">
      {/* 头部工具栏 - 固定 */}
      <div className="flex-shrink-0 mt-3">
        <div className="px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <HardDrive className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    选择存储源
                  </h1>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 - 可滚动 - 增加左右1%的margin */}
      <div className="flex-1 overflow-y-auto">
        <div className="px-4 py-6 mx-[1%]">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p className="text-material-grey-600">正在加载存储源...</p>
              </div>
            </div>
          ) : storageSources.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                <HardDrive className="w-8 h-8 text-material-grey-500" />
              </div>
              <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                暂无可用的存储源
              </h3>
              <p className="text-material-grey-500 mb-4">
                请联系管理员配置存储源
              </p>
              <Button 
                onClick={() => navigate('/storage/source')}
                variant="outline"
              >
                管理存储源
              </Button>
            </div>
          ) : (
            <div className="max-w-full mx-auto">
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-6">
                {storageSources.map((source) => {
                  const IconComponent = getStorageIcon(source.sourceCode);
                  const isAvailable = source.isEnabled === 1 && source.sourceStatus === 'ENABLED';
                  const isSelected = selectedSource?.sourceId === source.sourceId;
                  
                  return (
                    <Card 
                      key={source.sourceId}
                      className={`cursor-pointer transition-all duration-200 hover:shadow-lg ${
                        isSelected 
                          ? 'ring-2 ring-primary bg-primary/5' 
                          : isAvailable 
                            ? 'hover:border-primary/50' 
                            : 'opacity-60 cursor-not-allowed'
                      }`}
                      onClick={() => isAvailable && handleSelectSource(source)}
                      onDoubleClick={() => handleDoubleClickSource(source)}
                    >
                      <CardHeader className="pb-3">
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center space-x-3">
                            <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${
                              isSelected 
                                ? 'bg-gradient-to-br from-primary to-primary-600' 
                                : 'bg-gradient-to-br from-purple-100 to-purple-200'
                            }`}>
                              <IconComponent className={`w-6 h-6 ${
                                isSelected ? 'text-white' : 'text-purple-600'
                              }`} />
                            </div>
                            <div className="min-w-0 flex-1">
                              <div className="flex items-center space-x-2">
                                <CardTitle className="text-lg truncate">{source.sourceName}</CardTitle>
                                {source.isDefault === 1 && (
                                  <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100 flex-shrink-0">
                                    默认
                                  </Badge>
                                )}
                              </div>
                              <p className="text-sm text-material-grey-600 truncate">
                                {getStorageTypeName(source.sourceCode)}
                              </p>
                            </div>
                          </div>
                        </div>
                        
                        <div className="flex items-center justify-between">
                          {getStatusBadge(source.sourceStatus, source.isEnabled)}
                          {isSelected && (
                            <div className="flex items-center text-primary text-sm font-medium">
                              <CheckCircle className="w-4 h-4 mr-1" />
                              已选择
                            </div>
                          )}
                        </div>
                      </CardHeader>
                      
                      <CardContent className="pt-0">
                        <div className="space-y-2">
                          {source.sourceCode === 'LOCAL' ? (
                            <div className="text-sm text-material-grey-600">
                              <span className="font-medium">路径：</span>
                              <code className="bg-material-grey-100 px-1 rounded text-xs ml-1 break-all block mt-1">
                                {source.basePath || '/'}
                              </code>
                            </div>
                          ) : (
                            <>
                              {source.endpoint && (
                                <div className="text-sm text-material-grey-600">
                                  <span className="font-medium">端点：</span>
                                  <span className="ml-1 break-all block">{source.endpoint}</span>
                                </div>
                              )}
                              {source.bucketName && (
                                <div className="text-sm text-material-grey-600">
                                  <span className="font-medium">存储桶：</span>
                                  <span className="ml-1 break-all">{source.bucketName}</span>
                                </div>
                              )}
                              {source.region && (
                                <div className="text-sm text-material-grey-600">
                                  <span className="font-medium">区域：</span>
                                  <span className="ml-1 break-all">{source.region}</span>
                                </div>
                              )}
                            </>
                          )}
                          
                          {source.isPublic === 1 && (
                            <Badge variant="outline" className="mt-2">
                              公开
                            </Badge>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>

              {/* 选择提示 */}
              {selectedSource && (
                <div className="mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center space-x-3">
                    <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                      <CheckCircle className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <p className="font-medium text-blue-900">
                        已选择存储源：{selectedSource.sourceName}
                      </p>
                      <p className="text-sm text-blue-700">
                        双击存储源卡片直接进入文件管理
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default StorageSourceChoice;

